package org.hoyi.dispatchfact;

import java.lang.reflect.Constructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hoyi.DB.ctrl.Console;
import org.hoyi.dishop.Hoyipage;
import org.hoyi.dispatchs.responseUtil;
import org.hoyi.disptachs.model.JsonModel;
import org.hoyi.staticcache.HoyiPageStaticCache;
import org.hoyi.staticcache.ReqMapInfo;
import org.hoyi.wb.comment.RequestType;

public class MappingDispatcher implements IDispatcher{

	@Override
	public boolean doSth(HttpServletRequest _request, HttpServletResponse _response, String _requrl, RequestType _reqType) {
		String requesturi =  _request.getRequestURI().replaceFirst(_request.getContextPath(), "");
		//Console.Info("requestURI:" + requesturi);
		
		ReqMapInfo mapinfos = HoyiPageStaticCache.getInstance().GetMapByURI(requesturi);
		if(mapinfos == null)
			return false;
		
		Class disp  = mapinfos.reqclass;
		try {
			Constructor[] cons = disp.getConstructors();
			Hoyipage page = (Hoyipage) cons[0].newInstance(new Object[0]);
			page.reqmapinfo = mapinfos;

			// 这里读取到后，判断page能访问的类型是否包含在当前访问类型内.
			page.currentReqType = _reqType;
			page.InitAndLoadRequestType();
			// 如果验证能通过.
			if (page.ValidateReq()) {
				_request.setCharacterEncoding("UTF-8");
				page.setRequest(_request);
				page.setResponse(_response);
				page.OnPreInit();

				if (!page.Behaviored)
					;
			} else {
				JsonModel model = new JsonModel(-998, "Request Type is not allow.requesturl:" + _requrl);
				// JsonModel model = new JsonModel(-998, "Request Type is not allow." + file.getAbsolutePath() + ",requesturl:" + requrl);
				responseUtil.getinstance().WriteUTF8JSON(_response, model);
			}
			return true;
		} catch (Exception e) {
			Console.Error(e);
			return false;
		}
	}
}
